package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.views.IncomeDayReport;
import com.xmy.cultivate.entity.views.StatementData;
import com.xmy.cultivate.enums.SourseLeveEnum;
import com.xmy.cultivate.excel.ReturnPremiumDailySheet;
import com.xmy.cultivate.mapper.StudentGradeMapper;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.util.*;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 财务 前端控制器
 * </p>
 *
 * @author min
 * @since 2022-07-19
 */
@RestController
@RequestMapping("/api/finance")
@Scope("prototype")
public class FinanceController extends BaseController {

    @Autowired
    IOrderApplyService iOrderApplyService;

    @Autowired
    IOrderDetailService iOrderDetailService;

    @Autowired
    IFinanceService iFinanceService;

    @Autowired
    IQuarterService iQuarterService;

    @Autowired
    IStudentGradeService iStudentGradeService;

    @Autowired
    StudentGradeMapper studentGradeMapper;

    @Autowired
    @Lazy
    IEnrollInfoService iEnrollInfoService;

    @Autowired
    IRecordCourseService iRecordCourseService;

    @Autowired
    IOrderReturnTeacherService iOrderReturnTeacherService;

    /**
     * 收支明细
     *
     * @return
     */
    @GetMapping("/expensesAndReceipts")
    public Result expensesAndReceipts(@RequestParam Map reMap,
                                      @RequestParam(value = "yearPart", defaultValue = "") String yearPart,
                                      @RequestParam(value = "quarterNum", defaultValue = "") String quarterNum,
                                      @RequestParam(value = "schoolIdList", defaultValue = "") String[] schoolIdList,
                                      @RequestParam(value = "accountIdList", defaultValue = "") String[] accountIdList,
                                      @RequestParam(value = "statusList", defaultValue = "") String[] statusList,
                                      @RequestParam(value = "lessonType", defaultValue = "1", required = false) String lessonType) {
        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? 1 : Integer.valueOf((String) reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? 10 : Integer.valueOf((String) reMap.get("pageSize"));
        IPage<Map<String, Object>> iPage = new Page<>(pageNum, pageSize);

        String handleDateStart = (String) reMap.get("handleDateStart");
        String handleDateEnd = (String) reMap.get("handleDateEnd");

        String payDateStart = (String) reMap.get("payDateStart");
        String payDateEnd = (String) reMap.get("payDateEnd");

        QueryWrapper<Map<String, Object>> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(handleDateStart) && StringUtils.isNotBlank(handleDateEnd)) {
            queryWrapper.between("handle_date", handleDateStart, handleDateEnd);
        }

        if (StringUtils.isNotBlank(payDateStart) && StringUtils.isNotBlank(handleDateEnd)) {
            queryWrapper.between("created_at", payDateStart, handleDateEnd);
        }

        if (schoolIdList.length > 0) {
            queryWrapper.in("handle_school_id", schoolIdList);
        } else {
            queryWrapper.in("handle_school_id", this.baseSchoolIdList);
        }

        if (accountIdList.length > 0) {
            String accountIdStr = String.join(",", accountIdList);
            queryWrapper.inSql("id", "select order_id from order_pay_account where account_type in(" + accountIdStr + ")");
        }
        if (statusList.length > 0) {
            queryWrapper.in("status", statusList);
        } else {
            queryWrapper.ne("status", 2);
        }
        queryWrapper.eq(StringUtils.isNotBlank(lessonType), "lesson_type", lessonType);
        queryWrapper.eq(StringUtils.isNotBlank(yearPart), "year_part", yearPart);
        queryWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter_num", quarterNum);

        queryWrapper.eq("deleted", 0);

        iOrderApplyService.expensesAndReceipts(iPage, queryWrapper);
        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }

    /**
     * 交易列表
     *
     * @return
     */
    @GetMapping("/transaction")
    public Result transaction(@RequestParam Map reMap,
                              @RequestParam(value = "yearPart", defaultValue = "") String yearPart,
                              @RequestParam(value = "quarterNum", defaultValue = "") String quarterNum,
                              @RequestParam(value = "yearClassIdList", defaultValue = "") String[] yearClassIdList,
                              @RequestParam(value = "courseIdList", defaultValue = "") String[] courseIdList,
                              @RequestParam(value = "schoolIdList", defaultValue = "") String[] schoolIdList,
                              @RequestParam(value = "orderTypeList", defaultValue = "") String[] orderTypeList,
                              @RequestParam(value = "handlePersonId", defaultValue = "") String[] handlePersonId,
                              @RequestParam(value = "lessonType", defaultValue = "1", required = false) String lessonType) {
        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? 1 : Integer.valueOf((String) reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? 10 : Integer.valueOf((String) reMap.get("pageSize"));
        IPage<OrderApply> iPage = new Page<>(pageNum, pageSize);
        QueryWrapper<OrderApply> queryWrapper = new QueryWrapper<>();

        String handleDateStart = (String) reMap.get("handleDateStart");
        String handleDateEnd = (String) reMap.get("handleDateEnd");
        if (StringUtils.isNotBlank(handleDateStart) && StringUtils.isNotBlank(handleDateEnd)) {
            //queryWrapper.eq("handle_date",handleDate);
        }
        if (orderTypeList.length > 0) {
            queryWrapper.in("order_type", orderTypeList);
        }

        if (yearClassIdList.length > 0) {
            queryWrapper.in("year_class_id", yearClassIdList);
        }

        if (courseIdList.length > 0) {
            queryWrapper.in("course_id", courseIdList);
        }

        if (schoolIdList.length > 0) {
            queryWrapper.in("school_id", schoolIdList);
        } else {
            queryWrapper.in("school_id", this.baseSchoolIdList);
        }
        if (handlePersonId.length > 0) {
            queryWrapper.in("handle_person_id", handlePersonId);
        }
        queryWrapper.eq("deleted", 0);
        queryWrapper.ne("status", 2);
        queryWrapper.eq(StringUtils.isNotBlank(lessonType), "lesson_type", lessonType);
        queryWrapper.eq(StringUtils.isNotBlank(yearPart), "year_part", yearPart);
        queryWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter_num", quarterNum);

        iOrderApplyService.transaction(iPage, queryWrapper);
        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }

    /**
     * 确认收入列表
     *
     * @param reMap
     * @return
     */
    @GetMapping("/affirmIncome")
    public Result affirmIncome(@RequestParam Map reMap,
                               @RequestParam(value = "yearPart", defaultValue = "") String yearPart,
                               @RequestParam(value = "quarterNum", defaultValue = "") String quarterNum,
                               @RequestParam(value = "schoolIdList", defaultValue = "") String[] schoolIdList,
                               @RequestParam(value = "payTypeList", defaultValue = "") String[] payTypeList,
                               @RequestParam(value = "yearClassId", defaultValue = "") String yearClassId,
                               @RequestParam(value = "lessonType", defaultValue = "1", required = false) String lessonType) {
        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? 1 : Integer.valueOf((String) reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? 10 : Integer.valueOf((String) reMap.get("pageSize"));

        String startDate = reMap.get("startDate").toString();
        String endDate = reMap.get("endDate").toString();
        /*String orderType = reMap.get("orderType").toString();
        String status = reMap.get("status").toString();
        String isOwn = reMap.get("isOwn").toString();
        String keyType = reMap.get("keyType").toString();
        String keyWord = reMap.get("keyWord").toString();*/

        QueryWrapper<OrderApply> queryWrapper = new QueryWrapper<>();

        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(startDate)) {
            queryWrapper.between("handle_date", startDate, endDate);
        }
        //queryWrapper.eq(StringUtils.isNotBlank(isOwn),"isOwn",isOwn);

        if (schoolIdList.length > 0) {
            queryWrapper.in("handle_school_id", schoolIdList);
        } else {
            queryWrapper.in("handle_school_id", this.baseSchoolIdList);
        }

        queryWrapper.eq("status", 1);
        queryWrapper.eq("deleted", 0);
        queryWrapper.eq("order_type", 1);

        if (payTypeList.length > 0) {
            String typeStr = String.join(",", payTypeList);
            queryWrapper.inSql("id", "select order_id from order_pay_account where accoun_type in (" + typeStr + ")");
        }
        queryWrapper.eq(StringUtils.isNotBlank(lessonType), "lesson_type", lessonType);
        queryWrapper.eq(StringUtils.isNotBlank(yearPart), "year_part", yearPart);
        queryWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter_num", quarterNum);
        queryWrapper.orderByDesc("id");
        queryWrapper.inSql(StringUtils.isNotBlank(yearClassId), "year_class_id", yearClassId);

        IPage<OrderApply> iPage = new Page<>(pageNum, pageSize);
        iOrderApplyService.affirmIncome(iPage, queryWrapper);
        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }


    public Result dailyStatement(@RequestParam Map reMap,
                                 @RequestParam(value = "schoolIdList", defaultValue = "") String[] schoolIdList,
                                 @RequestParam(value = "payTypeList", defaultValue = "") String[] payTypeList,
                                 @RequestParam(value = "lessonType", defaultValue = "1", required = false) String lessonType) {
        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? 1 : Integer.valueOf((String) reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? 10 : Integer.valueOf((String) reMap.get("pageSize"));

        String startDate = reMap.get("startDate").toString();
        String endDate = reMap.get("endDate").toString();
        String orderType = reMap.get("orderType").toString();
        String status = reMap.get("status").toString();
        String isOwn = reMap.get("isOwn").toString();
        String keyType = reMap.get("keyType").toString();
        String keyWord = reMap.get("keyWord").toString();

        QueryWrapper<OrderApply> queryWrapper = new QueryWrapper<>();

        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(startDate)) {
            queryWrapper.between("handle_date", startDate, endDate);
        }
        queryWrapper.eq(StringUtils.isNotBlank(isOwn), "isOwn", isOwn);

        if (schoolIdList.length > 0) {
            queryWrapper.in("handle_school_id", schoolIdList);
        } else {
            queryWrapper.in("handle_school_id", this.baseSchoolIdList);
        }

        queryWrapper.eq("status", 1);

        if (payTypeList.length > 0) {
            String typeStr = String.join(",", payTypeList);
            queryWrapper.inSql("id", "select order_id from order_pay_account where accoun_type in (" + typeStr + ")");
        }

        queryWrapper.eq(StringUtils.isNotBlank(lessonType), "lesson_type", lessonType);
        IPage<OrderApply> iPage = new Page<>(pageNum, pageSize);
        iOrderApplyService.affirmIncome(iPage, queryWrapper);
        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }


    /**
     * 收入日报表
     *
     * @param reMap
     * @param schoolIdList
     * @param studentName
     * @param lessonType
     * @param yearClassId
     * @param isPrint      是否打印
     * @return
     */
    @GetMapping("incomeDayReport")
    public Result incomeDayReport(@RequestParam Map<String, String> reMap,
                                  @RequestParam(value = "yearPart", required = false) Integer yearPart,
                                  @RequestParam(value = "quarterNum", required = false) Integer quarterNum,
                                  @RequestParam(value = "startDate", required = false, defaultValue = "") String startDate,
                                  @RequestParam(value = "endDate", required = false, defaultValue = "") String endDate,
                                  @RequestParam(value = "subjectsId", required = false, defaultValue = "") String subjectsId,
                                  @RequestParam(value = "orderType", required = false, defaultValue = "") String orderType,
                                  @RequestParam(value = "schoolIdList", defaultValue = "") String[] schoolIdList,
                                  @RequestParam(value = "studentName", defaultValue = "", required = false) String studentName,
                                  @RequestParam(value = "lessonType", defaultValue = "1", required = false) String lessonType,
                                  @RequestParam(value = "yearClassId", defaultValue = "", required = false) String yearClassId,
                                  @RequestParam(value = "handlePersonId", defaultValue = "", required = false) String handlePersonId,
                                  @RequestParam(value = "payeeId", defaultValue = "", required = false) String payeeId,
                                  @RequestParam(value = "inviteId", defaultValue = "", required = false) String inviteId,// 邀约人
                                  @RequestParam(value = "status", defaultValue = "", required = false) String status,
                                  @RequestParam(value = "isPrint", defaultValue = "", required = false) String isPrint,
                                  @RequestParam(value = "payNum", defaultValue = "", required = false) String payNum,// 期数
                                  @RequestParam(value = "teacherId", defaultValue = "", required = false) String teacherId,
                                  @RequestParam(value = "readType", defaultValue = "0", required = false) Integer readType, // 0默认，1新生报名，2续报
                                  @RequestParam(value = "affirmMode", defaultValue = "", required = false) String affirmMode  //1手动确认，2自动确认
    ) {
        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? 1 : Integer.valueOf((String) reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? 10 : Integer.valueOf((String) reMap.get("pageSize"));

        String type = "1";//1日报表，2优惠表
        if (reMap.get("type") != null) {
            type = reMap.get("type");
        }

        QueryWrapper<OrderDetail> queryWrapper = new QueryWrapper<>();

        if (type.equals("1")) {
            //1日报表，2优惠表
            if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(startDate)) {
                queryWrapper.between("handle_date", startDate, endDate);
            }
            if (StringUtils.isNotBlank(status)) {
                queryWrapper.eq("status", status);
            }

            queryWrapper.eq(StringUtils.isNotBlank(affirmMode), "affirm_mode", affirmMode); // 1手动确认，2自动确认
        } else {
            if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(startDate)) {
                queryWrapper.between("discounts_date", startDate, endDate);
            }
            if (StringUtils.isNotBlank(status)) {
                if (status.equals("1")) {
                    //queryWrapper.eq("arrive_affirm", 2);
                    queryWrapper.and(i -> i.eq("arrive_affirm", 2).or().inSql("order_id", "select order_id from order_apply_affirm where type =1 and affirm_type=2"));
                } else {
                    queryWrapper.ne("arrive_affirm", 2);
                    queryWrapper.notInSql("order_id", "select order_id from order_apply_affirm where type =1 and affirm_type=2");
                }
            }
            //queryWrapper.eq("status", 1);
            queryWrapper.gt("discounts_price", 0);
        }

        if (StringUtils.isNotBlank(isPrint)) {
            if (isPrint.equals("1")) {
                queryWrapper.eq("is_print", 1);
            } else {
                queryWrapper.eq("is_print", 0);
            }
        }

//        if (StringUtils.isNotBlank(payNum)) {
//            queryWrapper.eq("pay_num", payNum);
//        }

        //queryWrapper.eq(StringUtils.isNotBlank(isOwn),"isOwn",isOwn);

        List<Long> schoolIdDis = new ArrayList<>();//优惠接口调整了，需要使用list格式
        if (schoolIdList.length > 0) {
            queryWrapper.in("school_id", schoolIdList);
            for (String id : schoolIdList) {
                schoolIdDis.add(Long.parseLong(id));
            }
        } else {
            queryWrapper.in("school_id", this.baseSchoolIdList);
            schoolIdDis = this.baseSchoolIdList;
        }

        queryWrapper.ne("status", 2);

        if (StringUtils.isNotBlank(subjectsId)) {
            queryWrapper.inSql("subjects_id", subjectsId);
        }

        //queryWrapper.eq("order_type",1);
        if (StringUtils.isNotBlank(orderType)) {
            queryWrapper.in("order_type", orderType);
        } else {
            queryWrapper.in("order_type", 1, 5);
        }

        queryWrapper.like(StringUtils.isNotBlank(studentName), "student_name", studentName);
        queryWrapper.inSql(StringUtils.isNotBlank(yearClassId), "year_class_id", yearClassId);

        //queryWrapper.eq("arrive_affirm",2);
        queryWrapper.orderByDesc("created_at");


        IPage<IncomeDayReport> iPage = new Page<>(pageNum, pageSize);

        queryWrapper.eq(StringUtils.isNotBlank(lessonType), "lesson_type", lessonType);
        queryWrapper.eq(StringUtils.isNotBlank(handlePersonId), "handle_person_id", handlePersonId);
        queryWrapper.eq(StringUtils.isNotBlank(payeeId), "payee_id", payeeId);

        Map<String, Object> map = new HashMap<>();
        if (type.equals("1")) {
            iOrderDetailService.getIncomeDayReport(iPage, queryWrapper, readType, payNum);
//            BigDecimal statisticsPrice = iOrderDetailService.getStatisticsPrice(queryWrapper);
            map.put("solidStatisticsPrice", iOrderDetailService.getIncomeDailyRsCount(queryWrapper));
        } else {
            List<Integer> yearClassIdList = new ArrayList<>();
            if (StringUtils.isNotBlank(yearClassId)) {
                yearClassIdList.add(Integer.parseInt(yearClassId));
            }
            iOrderDetailService.getDisList(iPage, yearPart, quarterNum, schoolIdDis, subjectsId, status, studentName, lessonType, yearClassIdList, handlePersonId, startDate, endDate, orderType, payeeId, inviteId, teacherId);
            BigDecimal disPrice = iOrderDetailService.getDisPrice(yearPart, quarterNum, schoolIdDis, subjectsId, status, studentName, lessonType, yearClassIdList, handlePersonId, startDate, endDate, orderType,payeeId, inviteId, teacherId);
            map.put("disPrice", disPrice);
        }


        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages(), map));
    }


    @GetMapping("incomeDayReportExport")
    public void incomeDayReportExport(@RequestParam Map<String, String> reMap,
                                      @RequestParam(value = "yearPart", required = false) Integer yearPart,
                                      @RequestParam(value = "quarterNum", required = false) Integer quarterNum,
                                      @RequestParam(value = "schoolIdList", defaultValue = "") String[] schoolIdList,
                                      @RequestParam(value = "studentName", defaultValue = "", required = false) String studentName,
                                      @RequestParam(value = "lessonType", defaultValue = "1", required = false) String lessonType,
                                      @RequestParam(value = "yearClassId", defaultValue = "", required = false) String yearClassId,
                                      @RequestParam(value = "handlePersonId", defaultValue = "", required = false) String handlePersonId,
                                      @RequestParam(value = "payeeId", defaultValue = "", required = false) String payeeId,
                                      @RequestParam(value = "inviteId", defaultValue = "", required = false) String inviteId,
                                      @RequestParam(value = "status", defaultValue = "", required = false) String status,
                                      @RequestParam(value = "isPrint", defaultValue = "", required = false) String isPrint,
                                      @RequestParam(value = "payNum", defaultValue = "", required = false) String payNum,// 期数
                                      @RequestParam(value = "teacherId", defaultValue = "", required = false) String teacherId,
                                      @RequestParam(value = "readType", defaultValue = "0", required = false) Integer readType // 0默认，1新生报名，2续报
    ) throws IOException {


        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? 1 : Integer.valueOf((String) reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? 100000 : Integer.valueOf((String) reMap.get("pageSize"));

        String startDate = reMap.get("startDate");
        String endDate = reMap.get("endDate");
        String subjectsId = reMap.get("subjectsId");
        String orderType = reMap.get("orderType");

        String type = "1";//1日报表，2优惠表
        if (reMap.get("type") != null) {
            type = reMap.get("type");
        }

        QueryWrapper<OrderDetail> queryWrapper = new QueryWrapper<>();

        if (type.equals("1")) {
            //1日报表，2优惠表
            if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(startDate)) {
                queryWrapper.between("handle_date", startDate, endDate);
            }
            if (StringUtils.isNotBlank(status)) {
                queryWrapper.eq("status", status);
            }
        } else {
            if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(startDate)) {
                queryWrapper.between("discounts_date", startDate, endDate);
            }
            if (StringUtils.isNotBlank(status)) {
                if (status.equals("1")) {
                    queryWrapper.eq("arrive_affirm", 2);
                } else {
                    queryWrapper.ne("arrive_affirm", 2);
                }
            }
            queryWrapper.eq("status", 1);
            queryWrapper.gt("discounts_price", 0);
        }

        if (StringUtils.isNotBlank(isPrint)) {
            if (isPrint.equals("1")) {
                queryWrapper.eq("is_print", 1);
            } else {
                queryWrapper.eq("is_print", 0);
            }
        }

        //queryWrapper.eq(StringUtils.isNotBlank(isOwn),"isOwn",isOwn);

        List<Long> schoolIdDis = new ArrayList<>();//优惠接口调整了，需要使用list格式
        if (schoolIdList.length > 0) {
            queryWrapper.in("school_id", schoolIdList);
            for (String id : schoolIdList) {
                schoolIdDis.add(Long.parseLong(id));
            }
        } else {
            queryWrapper.in("school_id", this.baseSchoolIdList);
            schoolIdDis = this.baseSchoolIdList;
        }

        queryWrapper.ne("status", 2);

        if (StringUtils.isNotBlank(subjectsId)) {
            queryWrapper.inSql("subjects_id", subjectsId);
        }

        //queryWrapper.eq("order_type",1);
        if (StringUtils.isNotBlank(orderType)) {
            queryWrapper.in("order_type", orderType);
        } else {
            queryWrapper.in("order_type", 1, 5);
        }

        queryWrapper.like(StringUtils.isNotBlank(studentName), "student_name", studentName);
        queryWrapper.inSql(StringUtils.isNotBlank(yearClassId), "year_class_id", yearClassId);

        //queryWrapper.eq("arrive_affirm",2);
        queryWrapper.orderByDesc("created_at");
        queryWrapper.eq(StringUtils.isNotBlank(lessonType), "lesson_type", lessonType);
        queryWrapper.eq(StringUtils.isNotBlank(handlePersonId), "handle_person_id", handlePersonId);
        queryWrapper.eq(StringUtils.isNotBlank(payeeId), "payee_id", payeeId);

        IPage<IncomeDayReport> iPage = new Page<>(pageNum, pageSize);


        if (type.equals("1")) {
            iOrderDetailService.getIncomeDayReport(iPage, queryWrapper, readType, payNum);
        } else {
            List<Integer> yearClassIdList = new ArrayList<>();
            if (StringUtils.isNotBlank(yearClassId)) {
                yearClassIdList.add(Integer.parseInt(yearClassId));
            }
            iOrderDetailService.getDisList(iPage, yearPart, quarterNum, schoolIdDis, subjectsId, status, studentName, lessonType, yearClassIdList, handlePersonId, startDate, endDate, orderType, payeeId, inviteId, teacherId);
        }

        List<IncomeDayReport> incomeDayReportList = iPage.getRecords();


        Workbook wb = new XSSFWorkbook();
        Sheet sheet = wb.createSheet();

        String[] titles = "收据编号,校区,学生姓名,年级,科目,收款人,收款日期,学费标准(元),已收学费(元),邀约,试听,成交".split(",");
        if (reMap.get("type") != null) {
            type = reMap.get("type").toString();
            if (type.equals("2")) {
                titles = "收据编号,校区,学生姓名,年级,科目,教师,收款人,优惠日期,学费标准(元),已收学费(元),优惠金额(元)".split(",");
            }
        }


        //处理标题
        Row row = sheet.createRow(0);
        int titleIndex = 0;
        for (String title : titles) {
            Cell cell = row.createCell(titleIndex++);
            cell.setCellValue(title);
        }

        Cell cell = null;
        int rowIndex = 1;
        int cellIndex = 0;
        for (IncomeDayReport incomeDayReport : incomeDayReportList) {
            cellIndex = 0;
            row = sheet.createRow(rowIndex++);

            cell = row.createCell(cellIndex);
            cell.setCellValue(incomeDayReport.getReceiptNo());
            cellIndex++;

            cell = row.createCell(cellIndex);
            cell.setCellValue(incomeDayReport.getSchoolName());
            cellIndex++;

            cell = row.createCell(cellIndex);
            cell.setCellValue(incomeDayReport.getStudentName());
            cellIndex++;

            cell = row.createCell(cellIndex);
            cell.setCellValue(incomeDayReport.getYearClassName());
            cellIndex++;

            cell = row.createCell(cellIndex);
            cell.setCellValue(incomeDayReport.getSubjectsName());
            cellIndex++;

            //优惠表
            if (type.equals("2")) {
                cell = row.createCell(cellIndex);
                cell.setCellValue(incomeDayReport.getTeacherName());
                cellIndex++;
            }

            cell = row.createCell(cellIndex);
            cell.setCellValue(incomeDayReport.getPayeeName());
            cellIndex++;

            cell = row.createCell(cellIndex);
            if (type.equals("1")) {
                cell.setCellValue(incomeDayReport.getHandleDate().toString());
            } else if (type.equals("2")) {
                cell.setCellValue(incomeDayReport.getDiscountsDate().toString());
            }
            cellIndex++;

            cell = row.createCell(cellIndex);
            cell.setCellValue(incomeDayReport.getCoursePriceName());
            cellIndex++;

            cell = row.createCell(cellIndex);
            cell.setCellValue(incomeDayReport.getPrice().toString());
            cellIndex++;

            //优惠表
            if (type.equals("2")) {
                cell = row.createCell(cellIndex);
                cell.setCellValue(incomeDayReport.getDiscountsPrice().toString());
                cellIndex++;
            }

            /*if (incomeDayReport.getDisPrice() != null) {
                cell = row.createCell(cellIndex);
                cell.setCellValue(incomeDayReport.getDisPrice().toString());
                cellIndex++;
            }*/

            //
            if (type.equals("1")) {
                cell = row.createCell(cellIndex);
                cell.setCellValue(incomeDayReport.getInviteNames());
                cellIndex++;

                cell = row.createCell(cellIndex);
                cell.setCellValue(incomeDayReport.getAuditionNames());
                cellIndex++;

                cell = row.createCell(cellIndex);
                cell.setCellValue(incomeDayReport.getBargainNames());
            }
        }
        //3.完成下载
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        wb.write(os);
        new DownloadUtils().download(os, response, "收入日报表.xlsx");
    }


    /**
     * 财务报表
     *
     * @param reMap
     * @return
     */
    @GetMapping("/statementData")
    public Result statementData(@RequestParam Map reMap,
                                @RequestParam(value = "lessonType", defaultValue = "1", required = false) String lessonType) {

        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? 1 : Integer.valueOf((String) reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? 10 : Integer.valueOf((String) reMap.get("pageSize"));

        String schoolId = (String) reMap.get("schoolId");
        String startDate = (String) reMap.get("startDate");
        String endDate = (String) reMap.get("endDate");
        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String subjectsId = (String) reMap.get("subjectsId");
        String studentName = (String) reMap.get("studentName");
        // 1停课，2结课，3退费，4转校，5异常，6在读
        String type = (String) reMap.get("type");

        if (StringUtils.isBlank(yearPart)) {
            return new Result(Code.ERROR, "", "年份不能为空");
        }

        if (StringUtils.isBlank(quarterNum)) {
            return new Result(Code.ERROR, "", "学期不能为空");
        }

        IPage<StatementData> iPage = new Page<>(pageNum, pageSize);

        // 在读
        if (StringUtils.isNotBlank(type) && type.equals("6")) {
            iFinanceService.statementDataStill(iPage, schoolId, startDate, endDate, subjectsId, studentName, yearPart, quarterNum, lessonType, type);
        } else if (StringUtils.isNotBlank(type) && type.equals("2")) {
            // 结课
            iFinanceService.statementDataEnd(iPage, schoolId, startDate, endDate, subjectsId, studentName, yearPart, quarterNum, lessonType, type);
        } else {
            iFinanceService.statementData(iPage, schoolId, startDate, endDate, subjectsId, studentName, yearPart, quarterNum, lessonType, type);
        }

        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }

    @GetMapping("/statementDataExport")
    public void statementDataExport(@RequestParam Map reMap,
                                    @RequestParam(value = "lessonType", defaultValue = "1", required = false) String lessonType) throws IOException {

        Integer pageNum = -1;
        Integer pageSize = -1;

        String schoolId = (String) reMap.get("schoolId");
        String startDate = (String) reMap.get("startDate");
        String endDate = (String) reMap.get("endDate");
        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String subjectsId = (String) reMap.get("subjectsId");
        String studentName = (String) reMap.get("studentName");
        // 1停课，2结课，3退费，4转校，5异常，6在读
        String type = (String) reMap.get("type");

        if (StringUtils.isBlank(yearPart)) {

        }

        if (StringUtils.isBlank(quarterNum)) {

        }

        IPage<StatementData> iPage = new Page<>(pageNum, pageSize);

        // 在读
        if (StringUtils.isNotBlank(type) && type.equals("6")) {
            iFinanceService.statementDataStill(iPage, schoolId, startDate, endDate, subjectsId, studentName, yearPart, quarterNum, lessonType, type);
        } else if (StringUtils.isNotBlank(type) && type.equals("2")) {
            // 结课
            iFinanceService.statementDataEnd(iPage, schoolId, startDate, endDate, subjectsId, studentName, yearPart, quarterNum, lessonType, type);
        } else {
            iFinanceService.statementData(iPage, schoolId, startDate, endDate, subjectsId, studentName, yearPart, quarterNum, lessonType, type);
        }

        List<String> headList = new ArrayList<>();
        headList.add("姓名");
        headList.add("年级");
        headList.add("总课次");
        headList.add("已上课次");
        headList.add("剩余课次");
        headList.add("收入");
        headList.add("优惠");
        headList.add("营业收入");
        headList.add("退费");
        headList.add("实际收入");
        headList.add("预收款");

        // 写入表头
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("赛道详情");
        CellStyle headerCellStyle = workbook.createCellStyle();
        Font headerFont = workbook.createFont();
        headerFont.setFontHeightInPoints((short) 11);
        headerCellStyle.setFont(headerFont);
        headerCellStyle.setAlignment(HorizontalAlignment.CENTER);
        headerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        Row headerRow = sheet.createRow(0);
        sheet.createFreezePane(0, 1);// 冻结首行

        for (int i = 0; i < headList.size(); i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headList.get(i));
            cell.setCellStyle(headerCellStyle);
        }

        // 创建顶部样式
        CellStyle cellStyle1 = workbook.createCellStyle();
        Font font1 = workbook.createFont();
        font1.setFontHeightInPoints((short) 11);
        cellStyle1.setFont(font1);
        cellStyle1.setAlignment(HorizontalAlignment.CENTER); // 水平居中
        cellStyle1.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中

        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFont(headerFont);
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        int rowIndex = 1; // 数据行起始索引

        for (StatementData statementData : iPage.getRecords()) {
            Row row = sheet.createRow(rowIndex);

            Cell cell = row.createCell(0);
            cell.setCellValue(statementData.getStudentName());
            sheet.setColumnWidth(0, 20 * 256);
            cell.setCellStyle(cellStyle);

            Cell cell1 = row.createCell(1);
            cell1.setCellValue(statementData.getYearClassName());
            sheet.setColumnWidth(1, 20 * 256);
            cell1.setCellStyle(cellStyle);

            Cell cell2 = row.createCell(2);
            if (statementData.getAllCourseCount() != null) {
                cell2.setCellValue((statementData.getAllCourseCount() / 3));
            } else {
                cell2.setCellValue(0);
            }
            sheet.setColumnWidth(2, 20 * 256);
            cell2.setCellStyle(cellStyle);

            Cell cell3 = row.createCell(3);
            if (statementData.getUseCourseCount() != null) {
                cell3.setCellValue((statementData.getUseCourseCount() / 3));
            } else {
                cell3.setCellValue(0);
            }
            sheet.setColumnWidth(3, 20 * 256);
            cell3.setCellStyle(cellStyle);

            Cell cell4 = row.createCell(4);
            if (statementData.getResidueCourseCount() != null) {
                cell4.setCellValue((statementData.getResidueCourseCount() / 3));
            } else {
                cell4.setCellValue(0);
            }
            sheet.setColumnWidth(4, 20 * 256);
            cell4.setCellStyle(cellStyle);

            Cell cell5 = row.createCell(5);
            if (statementData.getPrice() != null) {
                cell5.setCellValue(statementData.getPrice().toString());
            } else {
                cell5.setCellValue(0);
            }
            sheet.setColumnWidth(5, 20 * 256);
            cell5.setCellStyle(cellStyle);

            Cell cell6 = row.createCell(6);
            if (statementData.getDiscountsPrice() != null) {
                cell6.setCellValue(statementData.getDiscountsPrice().toString());
            } else {
                cell6.setCellValue(0);
            }
            sheet.setColumnWidth(6, 20 * 256);
            cell6.setCellStyle(cellStyle);

            Cell cell7 = row.createCell(7);
            if (statementData.getSolidPrice() != null) {
                cell7.setCellValue(statementData.getSolidPrice().toString());
            } else {
                cell7.setCellValue(0);
            }
            sheet.setColumnWidth(7, 20 * 256);
            cell7.setCellStyle(cellStyle);

            Cell cell8 = row.createCell(8);
            if (statementData.getOutPrice() != null) {
                cell8.setCellValue(statementData.getOutPrice().toString());
            } else {
                cell8.setCellValue(0);
            }
            sheet.setColumnWidth(8, 20 * 256);
            cell8.setCellStyle(cellStyle);

            Cell cell9 = row.createCell(9);
            if (statementData.getRealityPirce() != null) {
                cell9.setCellValue(statementData.getRealityPirce().toString());
            } else {
                cell9.setCellValue(0);
            }
            sheet.setColumnWidth(9, 20 * 256);
            cell9.setCellStyle(cellStyle);

            Cell cell10 = row.createCell(10);
            if (statementData.getAdvancePrice() != null) {
                cell10.setCellValue(statementData.getAdvancePrice().toString());
            } else {
                cell10.setCellValue(0);
            }
            sheet.setColumnWidth(10, 20 * 256);
            cell10.setCellStyle(cellStyle);

            rowIndex++;
        }
        String fileName = "财务报表" + ".xlsx";
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8");

        response.setContentType("application/zip");//设置为zip格式
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);//设置响应头

        // 获取响应输出流
        OutputStream outputStream = response.getOutputStream();

        // 将工作簿写入输出流
        workbook.write(outputStream);

        // 关闭工作簿
        workbook.close();

        // 刷新输出流
        outputStream.flush();

        //关闭输出流
        outputStream.close();
    }


    /**
     * 修改金额
     *
     * @return
     */
    @PostMapping("/updatePrice")
    public Result updatePrice(@RequestBody Map<String, Object> map,
                              @RequestParam(value = "lessonType", defaultValue = "1", required = false) String lessonType) {

        String schoolId = map.get("schoolId").toString();
        String studentId = map.get("studentId").toString();
        String subjectsId = map.get("subjectsId").toString();
        BigDecimal afterPrice = new BigDecimal(map.get("afterPrice").toString());
        BigDecimal beforePrice = new BigDecimal(map.get("beforePrice").toString());
        String yearPart = map.get("yearPart").toString();
        String quarterNum = map.get("quarterNum").toString();

        //LocalDate orderDate = LocalDate.parse(map.get("orderDate").toString());

        QueryWrapper<Quarter> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("year_part", yearPart);
        queryWrapper.eq("num", quarterNum);
        queryWrapper.last("limit 1");

        Quarter quarter = iQuarterService.getOne(queryWrapper);

        boolean rs = iFinanceService.updatePrice(schoolId, studentId, subjectsId, beforePrice, afterPrice, quarter, Integer.parseInt(lessonType));


        //System.out.println("schoolId:" + schoolId);
        //System.out.println("subjectsId:" + subjectsId);
        //System.out.println("afterPrice:" + afterPrice);
        return new Result(rs ? Code.OK : Code.ERROR, "", rs ? "修改成功" : "修改失败");
    }

    @GetMapping("/studentCount")
    @ApiOperation("学员状态统计")
    public Result countStudent(@RequestParam Map reMap,
                               @RequestParam(value = "lessonType", defaultValue = "1", required = false) String lessonType) {
        Map<String, String> map = new HashMap<>(6);

        //在读学员
        Integer inReadStudentCount = iStudentGradeService.inReadStudentCount(reMap, lessonType);
        map.put("inReadStudentCount", inReadStudentCount.toString());

        //异常学员
        Integer errorStudentCount = iStudentGradeService.abnormalStudentCount(reMap, lessonType);
        map.put("errorStudentCount", errorStudentCount.toString());

        //停课学员
        Integer stopStudentCount = iStudentGradeService.stopStudentCount(reMap, lessonType);
        map.put("stopStudentCount", stopStudentCount.toString());

        //退费学员
        Integer returnStudentCount = iStudentGradeService.returnStudentCount(reMap, lessonType);
        map.put("returnStudentCount", returnStudentCount.toString());

        //结课学员
        Integer overStudentCount = iStudentGradeService.overStudentCount(reMap, lessonType);
        map.put("overStudentCount", overStudentCount.toString());

        //转校学员
        Integer changeStudentCount = iStudentGradeService.changeStudentCount(reMap, lessonType);
        map.put("changeStudentCount", changeStudentCount.toString());

        return new Result(Code.GET_OK, map, "查询成功~");
    }

    /**
     * 退费或转校退费日报表
     *
     * @return
     * @throws InterruptedException
     */
    @GetMapping("/returnPremium")
    public Result returnPremium(@RequestParam Map reMap) {
        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? 1 : Integer.valueOf((String) reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? 10 : Integer.valueOf((String) reMap.get("pageSize"));
        IPage<ReturnPremiumDailySheet> iPage = new Page<>(pageNum, pageSize);

        String startDate = (String) reMap.get("startDate");
        String endDate = (String) reMap.get("endDate");
        String schoolIdList = (String) reMap.get("schoolIdList");
        String subjectsId = (String) reMap.get("subjectsId");
        String yearClassId = (String) reMap.get("yearClassId");
        String status = (String) reMap.get("status");//校长是否确认 0未确认 1已确认
        String isPrint = (String) reMap.get("isPrint");//是否打印小票 0未打印 1已打印
        String orderType = (String) reMap.get("orderType");// 退费类型 4退费 5转校退费,8转名额，转科目：9
        String studentName = (String) reMap.get("studentName");
        String teacherId = (String) reMap.get("teacherId");

        iOrderApplyService.getReturnPremiumDailySheet(iPage, orderType, startDate, endDate, schoolIdList, subjectsId, yearClassId, isPrint, studentName, status, teacherId);

        for (ReturnPremiumDailySheet premiumDailySheet : iPage.getRecords()) {
            /**
             * 邀约人
             */
            List<String> inviteNameList = iEnrollInfoService.getEnrollTeacher(premiumDailySheet.getOrderId(), 1);
            /**
             * 试听人
             */
            List<String> auditionNameList = iEnrollInfoService.getEnrollTeacher(premiumDailySheet.getOrderId(), 2);
            /**
             * 成交人
             */
            List<String> bargainNameList = iEnrollInfoService.getEnrollTeacher(premiumDailySheet.getOrderId(), 3);

            premiumDailySheet.setInviteNames(String.join(",", inviteNameList));
            premiumDailySheet.setAuditionNames(String.join(",", auditionNameList));
            premiumDailySheet.setBargainNames(String.join(",", bargainNameList));
        }

        Map<String, Object> map = new HashMap<>();
        BigDecimal statisticsPrice = iOrderApplyService.getReturnPremiumPrice(orderType, startDate, endDate, schoolIdList, subjectsId, yearClassId, isPrint, studentName, status, teacherId);
        map.put("solidStatisticsPrice", statisticsPrice);

        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages(), map));
    }

    /**
     * 同步退费的老师
     *
     * @return
     * @throws InterruptedException
     */
    @GetMapping("/saveReturnPremium")
    public Result saveReturnPremium() {
        QueryWrapper<OrderApply> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("apply_type", 4);
        //queryWrapper.eq("student_id",1763543703059693568L);
        queryWrapper.notInSql("id", "select order_id from order_return_teacher");
        List<OrderApply> applyList = iOrderApplyService.list(queryWrapper);

        for (OrderApply orderApply : applyList) {
            // 获取最后一次上课记录的老师
            RecordCourse recordCourse = iRecordCourseService.getRecordCourseByLastThreeQuarter(orderApply.getYearPart(), orderApply.getQuarterNum(), 1, orderApply.getStudentId(), String.valueOf(orderApply.getSubjectsIdStr()));
            if (recordCourse != null) {
                // 保存上课老师到表中
                OrderReturnTeacher orderReturnTeacher = new OrderReturnTeacher();
                orderReturnTeacher.setOrderId(orderApply.getId());
                orderReturnTeacher.setTeacherId(recordCourse.getOldTeacherId());
                iOrderReturnTeacherService.save(orderReturnTeacher);
            }
        }
        return new Result(Code.OK, "", Code.SAVE_OK_MSG);
    }

}
